'use strict';

const Service = require('egg').Service;
const path = require("path");
const sd = require('silly-datetime');
const mkdirp = require('mkdirp');

class ToolsService extends Service {
    /**
     * 获取文件上传目录
     * @param {*} filename
     */
    async getUploadFile(filename) {
        // 1.获取当前日期
        let day = sd.format(new Date(), 'YYYYMMDD');// 20210926
        // 2.创建图片保存的路径
        let dir = path.join(this.config.uploadDir, day);// app/public/avatar/upload/20210926
        await mkdirp(dir); // 不存在就创建目录 mkdir 本身不会反回一个promise所以不能使用await
        let date = Date.now(); // 毫秒数
        // 返回图片保存的路径
        let uploadDir = path.join(dir, date + path.extname(filename));  // path.extname(filename)文件后缀 .jpeg
        // app\public\avatar\upload\20210925\1632623852593
        return {
            uploadDir,
            saveDir: this.ctx.origin + uploadDir.slice(3).replace(/\\/g, '/')
        }
        // this.ctx.origin = http://localhost:7001 + \public\avatar\upload\20210925\1632623852593.jpeg
    }
}

module.exports = ToolsService;